import { Collection, CollectionService } from "@mallfoundry/catalog"
import { PageList } from "@mallfoundry/shared/data"
import * as _ from "lodash"
import { useEffect, useState } from "react"


interface UseCollectionsOptions {
  page?: number
  limit?: number
  storeId?: string
}

export function useCollections(options: UseCollectionsOptions) {
  const { page, limit, storeId } = options
  const [loading, setLoading] = useState(false)
  const [pageCollections, setPageCollections] = useState(PageList.empty<Collection>())
  useEffect(() => {
    setLoading(true)
    if (_.isUndefined(storeId)) {
      return
    }
    CollectionService.getCollections(
      CollectionService.createCollectionQuery()
        .toBuilder().page(page).limit(limit)
        .storeId(storeId).build())
      .then(setPageCollections)
      .finally(() => setLoading(false))
  }, [page, limit, storeId])
  return {
    loading,
    ...pageCollections,
  }
}
